package com.ioc;


import lombok.extern.log4j.Log4j2;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author SaErNuoSi
 * @date 2018/4/18 10:50
 */
@Log4j2
public class Scanner {

    private static final List<Class<?>> LIST = new ArrayList<>();
    private static final List<ClassDefine> CLASS_DEFINES = new ArrayList<>();
    private String root;

    public Scanner(String root) {
        this.root = root;
    }

    /**
     * 获取class对象列表
     *
     * @return
     */
    public List<ClassDefine> getClassDefines() {
        String filePath = packagePath2FilePath(root);
        URL resource = this.getClass().getClassLoader().getResource(filePath);
        String path = decode(resource.getPath());
        System.out.println(path);
        fillClassList(path);
        LIST.forEach(clazz -> {
            CLASS_DEFINES.add(new ClassDefine(clazz));
        });
        return CLASS_DEFINES;
    }

    /**
     * 通过一个文件路径获取下面的所有class
     *
     * @param path
     */
    private void fillClassList(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        } else if (file.isDirectory()) {
            Stream.of(file.listFiles()).forEach(val -> fillClassList(val.getPath()));
        } else {
            String substring = file.getPath().substring(file.getPath().indexOf(packagePath2FilePath(root)));
            //log.info("读取到文件路径: [{}]", substring);
            if (substring.endsWith(".class")) {
                try {
                    LIST.add(Class.forName(filePath2PackagePath(substring)));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String packagePath2FilePath(String packagePath) {
        return packagePath.replace(".", File.separator);

    }

    public String filePath2PackagePath(String filePath) {
        return filePath.replace(File.separator, ".").replace(".class", "");
    }

    public String decode(String uri) {
        try {
            return URLDecoder.decode(uri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }
}
